//
//  MZYSetUpViewController.m
//  WristWatch
//
//  Created by dllo on 15/10/22.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MZYSetUpViewController.h"
#import "MZYHeader.h"
// 夜间模式
#import "AppDelegate.h"
// 三方登录
#import "UMSocial.h"
// 意见反馈
#import <MessageUI/MessageUI.h>
#import "MZYcollectViewController.h"
@interface MZYSetUpViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, MFMailComposeViewControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
// UIActionSheetDelegate, UIImagePickerControllerDelegate 本地相册协议
// MFMailComposeViewControllerDelegate 意见反馈协议
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UIImageView *imageView;
@property(nonatomic, retain)NSArray *arr;
@property(nonatomic, retain)UIImageView *nameImageView;

@end

@implementation MZYSetUpViewController

- (void)dealloc {
    [_tableView release];
    [_imageView release];
    [_arr release];
    [_nameImageView release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的";
    
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.tableView];
//    self.tableView.backgroundColor = [UIColor redColor];
    [self.tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
    self.tableView.tableHeaderView = self.imageView;
    self.imageView.image = [UIImage imageNamed:@"15.jpg"];
    self.imageView.userInteractionEnabled = YES;
    [self.imageView release];
//
//    self.nameImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH / 2 - 50, 10, 100, 100)];
//    self.nameImageView.image = [UIImage imageNamed:@"16.jpg"];
//    [self.imageView addSubview:self.nameImageView];
//    self.nameImageView.layer.cornerRadius = 50;
//    self.nameImageView.layer.masksToBounds = YES;
//    
//    self.nameImageView.userInteractionEnabled = YES;
    // 长按手势
//    UILongPressGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
//    [self.nameImageView addGestureRecognizer:longpress];
//    [longpress release];
//    longpress.minimumPressDuration = 1;
    
    


    
    
    self.arr = @[@"我的收藏", @"清除缓存", @"意见反馈", @"夜间模式"];
    
}

#pragma mark 本地相册 图片相关
//- (void)longPressAction: (UILongPressGestureRecognizer *)longPress {
//
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//        
//        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"从相册里选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//            //可编辑
//            picker.allowsEditing = YES;
//            // 要通过choose获取本地的图片就必须签订协议
//            picker.delegate = self;
//            // 模态显示出来
//            [self presentViewController:picker animated:YES completion:^{
//                
//            }];
//        }];
//        [alert addAction:alertAction];
//    UIAlertAction *alertCamera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//        //可编辑
//        picker.allowsEditing = YES;
//        // 要通过choose获取本地的图片就必须签订协议
//        picker.delegate = self;
//        //设置相机模式
//        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//        // 模态显示出来
//        [self presentViewController:picker animated:YES completion:^{
//            
//        }];
//    }];
//    [alert addAction:alertCamera];
//        UIAlertAction *alertaction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//            NSLog(@"aaa");
//        }];
//        [alert addAction:alertaction];
//        [self presentViewController:alert animated:YES completion:^{
//            
//            
//        }];
//
//}
//
//
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//    // 先关闭相册消失
//    [picker dismissViewControllerAnimated:YES completion:nil];
//    //
//    UIImage *image = info[UIImagePickerControllerOriginalImage];
//    self.nameImageView.image = image;
//}

#pragma mark tableView两个协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *lreuse = @"lreuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:lreuse];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:lreuse] autorelease];
    }
    cell.textLabel.text = self.arr[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark tableView的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 3) {
        // 假夜间
        [(AppDelegate *)[UIApplication sharedApplication].delegate change];
    }else if (indexPath.row == 1) {
        // 创建一个文件管理者
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"%@", cachePath);
        CGFloat cacheSize = [self folderSizeAtPath:cachePath];
        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@%.2fM", @"清除共", cacheSize] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@%.2fM", @"清除共", cacheSize] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self clearCache:cachePath];
        }];
        [alert addAction:alertok];
        UIAlertAction *alertaction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"aaa");
        }];
        [alert addAction:alertaction];
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
        
        [self.tableView reloadData];
        
    } else if (indexPath.row == 2) {
        Class mailClass = NSClassFromString(@"MFMailComposeViewController");
        if (mailClass) {
            if ([mailClass canSendMail]) {
                // 如果有邮箱账户
                [self displayMailBox];
            } else {
                // 没有邮箱账户
                [self showMailBoxOnDevice];
            }
        } else {
            [self showMailBoxOnDevice];
        }

    } else if (indexPath.row == 0) {
        MZYcollectViewController *collectVC = [[MZYcollectViewController alloc] init];
        [self.navigationController pushViewController:collectVC animated:YES];
        [collectVC release];
    }
}


#pragma mark 版本检测
//- (NSString *)getCurrentLocalVersion
//{
//    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
//    NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
//    return appVersion;
//}

#pragma mark 意见反馈
// 打开设备自带的邮箱工具
- (void)showMailBoxOnDevice {
    NSString *mail = @"343267392qq.com";
    mail = [mail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mail]];
}

- (void)displayMailBox {
    // 创建邮件视图VC
    MFMailComposeViewController *mailBox = [[MFMailComposeViewController alloc] init];
    // 填写收件人地址
    NSArray *recipient = [NSArray arrayWithObject:@"343267392@qq.com"];
    [mailBox setToRecipients:recipient];
    // 填写主题
    [mailBox setSubject:@"意见反馈"];
    // 填写邮件内容
    NSString *messageBody = @"";
    [mailBox setMessageBody:messageBody isHTML:YES];
    // 添加一个文件
    UIImage *image = [UIImage imageNamed:@""];
    NSData *data = UIImagePNGRepresentation(image);
    [mailBox addAttachmentData:data mimeType:@"" fileName:@"随便填.jpg"];
    // 设置代理人
    mailBox.mailComposeDelegate = self;
    
    [self presentViewController:mailBox animated:YES completion:^{
    }];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    NSString *message;
    switch (result) {
        case MFMailComposeResultCancelled:
            message = @"取消发送";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultSaved:
            message = @"保存草稿";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultSent:
            message = @"已发送";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultFailed:
            message = @"发送失败";
            NSLog(@"%@", message);
            break;
            
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}





#pragma mark 清除缓存
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        NSLog(@"0");
    }else if (buttonIndex == 1) {
        // 创建一个文件管理者
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        [self clearCache:cachePath];
    }
    
    
}
-(void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}
- (float )folderSizeAtPath:(NSString *)folderPath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0 * 1024.0);
}

- (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
